#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>
#include <pthread.h>
using namespace std;

string gain_ID(const pthread_t &thread_tid)
{
    char buffer[128];
    snprintf(buffer, sizeof(buffer), "0x%x", thread_tid);
    return buffer;
}

void *start_routine(void *args)
{
    // 新线程
    string thread_name = static_cast<const char *>(args);
    int cnt = 5;
    while (cnt)
    {
        sleep(1);
        cout << "new thread sucess ..." << gain_ID(pthread_self()) << "  "
             << "cnt: " << cnt << endl;
        cnt--;
    }

    return nullptr;
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, nullptr, start_routine, (void *)"thread one");
    // 主线程
    cout << "main thread name: " << gain_ID(pthread_self()) << endl;
    //对新线程进行分离
    pthread_detach(tid);

    while(true)
    {
        //主线程做的事
        sleep(1);
        cout << "main thread name: " << gain_ID(pthread_self()) << endl;
    }

    // 对新线程进行，回收
    //int n = pthread_join(tid, nullptr); // 返回值为nullptr
    //cout << "result " << n << " " << strerror(n) << endl;
    return 0;
}
